/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.demo.domain;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.business.account.facade.enums.AccountStatus;
import info.peigen.hotpot.business.account.facade.enums.AccountType;
import info.peigen.hotpot.business.router.facade.enums.ChannelCode;
import info.peigen.hotpot.common.core.domain.DomainObject;
import info.peigen.hotpot.common.core.enums.Currency;
import info.peigen.hotpot.common.core.lang.money.Money;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import lombok.experimental.SuperBuilder;

import static info.peigen.hotpot.business.account.facade.enums.AccountStatus.Normal;
import static info.peigen.hotpot.business.router.facade.enums.ChannelCode.Weixin;
import static info.peigen.hotpot.common.core.enums.Currency.CNY;

/**
 * <b>(Account)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2021/8/10
 */
@SuppressWarnings("unused")
@SuperBuilder
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@Accessors(chain = true)
public class Account extends DomainObject {
    /** customerId */
    @NotEmpty
    String        customerId;
    /** 账户号,如果是客户账户则和customerId一致;备付金账户没有customerId,且号码特殊 */
    @NotEmpty
    String        accountId;
    /** 账户类型 */
    @NotNull
    AccountType   accountType;
    /** 账户状态 */
    @Builder.Default
    AccountStatus status   = Normal;
    /** 账户币种 */
    @Builder.Default
    Currency      currency = CNY;
    /** 余额 */
    @Builder.Default
    Money         balance  = Money.zero();

    // ----------- 备付金账户 -----------
    /** 账户别名 */
    String aliasName;
    /** 渠道编码 */
    @Builder.Default
    ChannelCode code = Weixin;

    // ----------- 客户账户 -----------
    /** 冻结资金 */
    @Builder.Default
    Money freezeAmount        = Money.zero();
    /** 在途资金 */
    @Builder.Default
    Money transitAmount       = Money.zero();
    /** 信用额度 */
    @Builder.Default
    Money creditQuotaAmount   = Money.zero();
    /** 待入账金额 */
    @Builder.Default
    Money pendingAmount       = Money.zero();
    /** 历史收入总金额 */
    @Builder.Default
    Money historyIncomeAmount = Money.zero();
    /** 历史支出总金额 */
    @Builder.Default
    Money historyPaidAmount   = Money.zero();
    /** memo */
    String memo;

    /**
     * 统一设置币种
     *
     * @param currency 币种
     */
    public void setAllCurrency(Currency currency) {
        this.currency = currency;
        this.balance = Money.zero(currency);
        this.transitAmount = Money.zero(currency);
        this.freezeAmount = Money.zero(currency);
        this.creditQuotaAmount = Money.zero(currency);
        this.historyIncomeAmount = Money.zero(currency);
        this.historyPaidAmount = Money.zero(currency);
    }

    @Override
    public void check() {
        super.check();
        if (accountType != AccountType.Provisions) {
            Assert.isTrue(StrUtil.isNotEmpty(getPartnerId()));
        }
        Assert.isTrue(this.status == Normal, () -> new BusinessException(ResultCode.FAILURE, "账户状态不正常[status=" + status.message() + "]"));
    }

    /**
     * 账户收入
     *
     * @param amount 金额
     */
    public void income(Money amount) {
        currencyIsSame(amount);
        balance.addTo(amount);
        historyIncomeAmount.addTo(amount);
    }

    /**
     * 账户支出
     *
     * @param amount 金额
     */
    public void paid(Money amount) {
        currencyIsSame(amount);
        checkBalanceShallNotBeNegative(balance);
        checkBalanceGreaterThan(balance, amount);
        balance.subtractFrom(amount);
        historyPaidAmount.addTo(amount);
    }

    /**
     * 账户资金冻结
     *
     * @param amount 金额
     */
    public void freezeCapital(Money amount) {
        currencyIsSame(amount);
        checkBalanceShallNotBeNegative(balance);
        checkBalanceGreaterThan(balance, amount);
        balance.subtractFrom(amount);
        freezeAmount.addTo(amount);
    }

    /**
     * 账户资金解冻
     *
     * @param amount 金额
     */
    public void unfreezeCapital(Money amount) {
        currencyIsSame(amount);
        balance.addTo(amount);
        checkBalanceShallNotBeNegative(freezeAmount);
        checkBalanceGreaterThan(freezeAmount, amount);
        freezeAmount.subtractFrom(amount);
    }

    /**
     * 判断币种
     *
     * @param amount 金额
     */
    private void currencyIsSame(Money amount) {
        Assert.isTrue(currency == amount.getCurrency());
        Assert.isTrue(balance.getCurrency() == amount.getCurrency());
    }

    /**
     * 判断币种
     *
     * @param amountA 金额
     * @param amountB 金额
     */
    private boolean currencyIsSame(Money amountA, Money amountB) {
        return amountA.getCurrency() == amountB.getCurrency();
    }

    /**
     * 余额不得为负数检查
     *
     * @param balance 余额
     */
    private void checkBalanceShallNotBeNegative(Money balance) {
        Assert.isTrue(balance.getCent() >= 0, "账户[{}]余额不得小于零", accountId);
    }

    /**
     * 交易检查
     *
     * @param balance 余额
     * @param amount  交易金额
     */
    private void checkBalanceGreaterThan(Money balance, Money amount) {
        Assert.isTrue(balance.getCent() >= amount.getCent(), "账户[{}]余额[{}]不得小于[{}]", accountId, balance, amount);
    }
}